package com.kc.sys.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kc.sys.common.*;
import com.kc.sys.domain.Permission;
import com.kc.sys.domain.Role;
import com.kc.sys.service.PermissionService;
import com.kc.sys.service.RoleService;
import com.kc.sys.vo.RoleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 老杜
 * @since 2019-10-23
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    /********************************************角色管理开始********************************************/


    @RequestMapping("loadAllRole")
    public DataGridView loadAllRole(RoleVo roleVo){

        //获取用户session
        //User user = (User)WebUtils.getSession().getAttribute("user");
        IPage<Role> page = new Page<>(roleVo.getPage(),roleVo.getLimit());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(roleVo.getName()),"name",roleVo.getName());
        queryWrapper.like(StringUtils.isNotBlank(roleVo.getRemark()),"remark",roleVo.getRemark());
        queryWrapper.orderByAsc("createtime");
        roleService.page(page,queryWrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    //添加角色
    @RequestMapping("addRole")
    public R addRole(RoleVo roleVo){
        try {
            roleVo.setCreatetime(new Date());
            roleService.save(roleVo);
            return R.ok().message("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("添加失败");
        }
    }

    //更新角色
    @RequestMapping("updateRole")
    public R updateRole(RoleVo roleVo){
        try {
            roleService.updateById(roleVo);
            return R.ok().message("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("更新失败");
        }
    }
    /**
     * 根据Id 删除
     * */
    @RequestMapping("deleteRole")
    public R deleteById(Integer id){
        try {
            roleService.removeById(id);
            return R.ok().message("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("删除失败");
        }
    }

    /**
     * 根据角色Id加载菜单和权限树的json串
     * */

    @RequestMapping("/initPermissionByRoleId")
    public DataGridView initPermissionByRoleId(Integer roleId){
        //查询所有可用的菜单和权限

        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        List<Permission> list = permissionService.list(queryWrapper);
        /*
        *1.根据角色Id查询当前角色拥有的所有的权限或菜单Id
        * 2.根据查询出来的菜单Id查询权限和菜单数据
        *根据角色Id查询当前角色拥有的权限和菜单
        */
        List<Permission> permissions = null;
        List<Integer> currentRolePermissions = this.roleService.queryRolePermissionIdsByRid(roleId);
        if(currentRolePermissions.size()>0){
            queryWrapper.in("id",currentRolePermissions);
            permissions = permissionService.list(queryWrapper);
        }else {
            permissions = new ArrayList<>();
        }

        //构造List<TreeNode>
        List<TreeNodeCheckArr> nodes = new ArrayList<>();
        for (Permission p1 : list) {
            String checkArr = "0";
            for (Permission p2 : permissions) {
                if(p1.getId()==p2.getId()){
                    checkArr="1";
                    break;
                }
            }
            Boolean spread=(p1.getOpen()==null||p1.getOpen()==1)?true:false;
            nodes.add(new TreeNodeCheckArr(p1.getId(),p1.getPid(),p1.getTitle(),spread,checkArr));
        }
        return new DataGridView(nodes);

    }

    /**
     *  保存角色和菜单权限之间的关系
     * */
    @RequestMapping("saveRolePermission")
    public R saveRolePermission(Integer rid, Integer[] ids) {

        try {
            roleService.saveRolePermission(rid,ids);
            return R.ok().message("分配成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("分配失败");
        }
    }
        /********************************************角色管理结束********************************************/
}

